package com.itheima.controller;

import com.itheima.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController {

    //接收用户数据,用户有校验注解

    /*
    *  步骤1: 实体类属性加校验注解
    *  步骤2: handle(@Validated实体类 对象)
    *  细节: param | json 校验注解都有效果
    *       json参数 - @RequestBody
    *
    * 如果: 不符合校验规则,直接想前段抛出异常
    * 接收错误绑定信息!自定义返回结果! 约定: 参数错误 -> {code:400} ->前端
    * 捕捉错误绑定错误信息
    *    1.handle{校验对象,BindingResult result) 要求: binDingResult必须紧挨着 校验对象
    *    2.bindingResult获取绑定错误
    *
    * */
    @RequestMapping("register")
    public Object register(@Validated @RequestBody User user, BindingResult result){

        if(result.hasErrors()){
            //有绑定错误,就不直接返回了,由我们自己决定!
            Map data = new HashMap();
            data.put("code",400);
            data.put("msg","参数校验异常");
            return data;
        }
        System.out.println("user = " + user);
        return user;
    }

    @RequestMapping("data")
    public String data(){
        //空指针异常
        String name = null;
        System.out.println("UserController.data");
        //
        // name.toString();
        return "ok";
    }

    @RequestMapping("data1")
    public String data1(){
        //算数异常
        int i = 1/0;
        return "ok";
    }
}
